// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 更新任务统计
    updateTaskStatistics();
    // 更新效率数据
    updateEfficiencyData();
    // 更新利用率数据
    updateUtilizationData();
    // 更新进度数据
    updateProgressData();
    // 渲染任务列表
    renderTaskList();
    // 绑定事件监听器
    bindEventListeners();
    // 设置定时更新
    setInterval(updateData, 30000);
});

// 更新效率数据
function updateEfficiencyData() {
    document.getElementById('qcEfficiency').textContent = `${taskData.efficiency.data[0].value[0]}%`;
    document.getElementById('rtgEfficiency').textContent = `${taskData.efficiency.data[0].value[1]}%`;
    document.getElementById('agvEfficiency').textContent = `${taskData.efficiency.data[0].value[2]}%`;
}

// 更新利用率数据
function updateUtilizationData() {
    document.getElementById('qcUtilization').textContent = `${taskData.utilization.data[0].value[0]}%`;
    document.getElementById('rtgUtilization').textContent = `${taskData.utilization.data[0].value[1]}%`;
    document.getElementById('agvUtilization').textContent = `${taskData.utilization.data[0].value[2]}%`;
}

// 更新进度数据
function updateProgressData() {
    document.getElementById('loadingProgress').textContent = `${taskData.progress.data[0].value[0]}%`;
    document.getElementById('unloadingProgress').textContent = `${taskData.progress.data[0].value[1]}%`;
    document.getElementById('transferProgress').textContent = `${taskData.progress.data[0].value[2]}%`;
}

// 更新数据
function updateData() {
    // 模拟数据更新
    taskData.statistics.runningTasks = Math.floor(Math.random() * 5) + 5;
    taskData.statistics.waitingTasks = Math.floor(Math.random() * 3) + 2;
    taskData.statistics.completedTasks = Math.floor(Math.random() * 3) + 1;
    taskData.statistics.totalTasks = taskData.statistics.runningTasks +
        taskData.statistics.waitingTasks +
        taskData.statistics.completedTasks;

    // 更新效率数据
    taskData.efficiency.data[0].value = [
        Math.floor(Math.random() * 5) + 90, // 岸桥效率 90-95%
        Math.floor(Math.random() * 5) + 85, // 龙门吊效率 85-90%
        Math.floor(Math.random() * 5) + 87 // AGV效率 87-92%
    ];

    // 更新利用率数据
    taskData.utilization.data[0].value = [
        Math.floor(Math.random() * 5) + 80, // 岸桥利用率 80-85%
        Math.floor(Math.random() * 5) + 73, // 龙门吊利用率 73-78%
        Math.floor(Math.random() * 5) + 77 // AGV利用率 77-82%
    ];

    // 更新进度数据
    taskData.progress.data[0].value = [
        Math.floor(Math.random() * 5) + 70, // 装船进度 70-75%
        Math.floor(Math.random() * 5) + 55, // 卸船进度 55-60%
        Math.floor(Math.random() * 5) + 40 // 转运进度 40-45%
    ];

    // 更新显示
    updateTaskStatistics();
    updateEfficiencyData();
    updateUtilizationData();
    updateProgressData();
    renderTaskList();
}

// 更新任务统计
function updateTaskStatistics() {
    document.getElementById('totalTasks').textContent = taskData.statistics.totalTasks;
    document.getElementById('runningTasks').textContent = taskData.statistics.runningTasks;
    document.getElementById('waitingTasks').textContent = taskData.statistics.waitingTasks;
    document.getElementById('completedTasks').textContent = taskData.statistics.completedTasks;
}

// 渲染任务列表
function renderTaskList() {
    const taskList = document.getElementById('taskList');
    taskList.innerHTML = '';

    taskData.tasks.forEach(task => {
        const taskElement = createTaskElement(task);
        taskList.appendChild(taskElement);
    });
}

// 创建任务元素
function createTaskElement(task) {
    const div = document.createElement('div');
    div.className = 'task-item';
    div.dataset.taskId = task.id;
    div.innerHTML = `
        <div class="task-header">
            <span class="task-title">${task.type} - ${task.vesselId}</span>
            <span class="task-status status-${task.status}">${getStatusText(task.status)}</span>
        </div>
        <div class="task-info">
            <span>开始时间: ${task.startTime}</span>
            <span>预计完成: ${task.endTime}</span>
            <span>集装箱数: ${task.containerCount}</span>
        </div>
        <div class="task-progress">
            <div class="progress-bar">
                <div class="progress" style="width: ${task.progress}%"></div>
            </div>
            <span>${task.progress}%</span>
        </div>
    `;
    return div;
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        running: '进行中',
        waiting: '待分配',
        completed: '已完成'
    };
    return statusMap[status] || status;
}

// 显示任务详情
function showTaskDetail(taskId) {
    const task = taskData.tasks.find(t => t.id === taskId);
    if (!task) return;

    const detailPanel = document.querySelector('.task-detail');
    detailPanel.classList.add('active');

    // 更新任务信息
    document.getElementById('taskId').textContent = task.id;
    document.getElementById('taskType').textContent = task.type;
    document.getElementById('taskStatus').textContent = getStatusText(task.status);
    document.getElementById('taskStartTime').textContent = task.startTime;
    document.getElementById('taskEndTime').textContent = task.endTime;
    document.getElementById('taskProgress').style.width = `${task.progress}%`;
    document.getElementById('progressText').textContent = `${task.progress}%`;

    // 更新设备列表
    const deviceList = document.getElementById('taskDevices');
    deviceList.innerHTML = task.devices.map(device => `
        <div class="device-item">
            <div class="device-icon">${device.type[0]}</div>
            <div class="device-info">
                <div class="device-name">${device.name}</div>
                <div class="device-status">效率: ${device.efficiency}%</div>
            </div>
        </div>
    `).join('');

    // 更新按钮状态
    updateTaskButtons(task.status);
}

// 更新任务按钮状态
function updateTaskButtons(status) {
    const pauseBtn = document.getElementById('pauseTaskBtn');
    const resumeBtn = document.getElementById('resumeTaskBtn');
    const cancelBtn = document.getElementById('cancelTaskBtn');

    pauseBtn.style.display = status === 'running' ? 'block' : 'none';
    resumeBtn.style.display = status === 'paused' ? 'block' : 'none';
    cancelBtn.style.display = status !== 'completed' ? 'block' : 'none';
}

// 绑定事件监听器
function bindEventListeners() {
    // 任务列表点击事件
    document.getElementById('taskList').addEventListener('click', (e) => {
        const taskItem = e.target.closest('.task-item');
        if (taskItem) {
            showTaskDetail(taskItem.dataset.taskId);
        }
    });

    // 关闭详情按钮
    document.getElementById('closeDetail').addEventListener('click', () => {
        document.querySelector('.task-detail').classList.remove('active');
    });

    // 新建任务按钮
    document.getElementById('addTaskBtn').addEventListener('click', () => {
        document.getElementById('newTaskModal').classList.add('active');
    });

    // 关闭模态框按钮
    document.querySelector('.close-modal').addEventListener('click', () => {
        document.getElementById('newTaskModal').classList.remove('active');
    });

    // 取消新建任务按钮
    document.getElementById('cancelNewTask').addEventListener('click', () => {
        document.getElementById('newTaskModal').classList.remove('active');
    });

    // 新建任务表单提交
    document.getElementById('newTaskForm').addEventListener('submit', (e) => {
        e.preventDefault();
        // 这里添加新建任务的逻辑
        document.getElementById('newTaskModal').classList.remove('active');
    });

    // 任务状态筛选
    document.getElementById('taskStatusFilter').addEventListener('change', filterTasks);
    // 任务类型筛选
    document.getElementById('taskTypeFilter').addEventListener('change', filterTasks);
}

// 筛选任务
function filterTasks() {
    const statusFilter = document.getElementById('taskStatusFilter').value;
    const typeFilter = document.getElementById('taskTypeFilter').value;

    const filteredTasks = taskData.tasks.filter(task => {
        const statusMatch = statusFilter === 'all' || task.status === statusFilter;
        const typeMatch = typeFilter === 'all' || task.type === typeFilter;
        return statusMatch && typeMatch;
    });

    const taskList = document.getElementById('taskList');
    taskList.innerHTML = '';
    filteredTasks.forEach(task => {
        const taskElement = createTaskElement(task);
        taskList.appendChild(taskElement);
    });
}